package de.teamgamma.cansat.groundstation.export;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Chart;
import org.apache.poi.ss.usermodel.ClientAnchor;
import org.apache.poi.ss.usermodel.Drawing;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.charts.AxisPosition;
import org.apache.poi.ss.usermodel.charts.ChartAxis;
import org.apache.poi.ss.usermodel.charts.ChartDataSource;
import org.apache.poi.ss.usermodel.charts.ChartLegend;
import org.apache.poi.ss.usermodel.charts.DataSources;
import org.apache.poi.ss.usermodel.charts.LegendPosition;
import org.apache.poi.ss.usermodel.charts.ScatterChartData;
import org.apache.poi.ss.usermodel.charts.ValueAxis;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import de.teamgamma.cansat.groundstation.livestream.TransmittedValue;

/**
 * Exporter for .xls
 * @author Marc Huisinga
 *
 */
public class XlsExporter implements Exporter {

	@Override
	public void export(ExportableData input, File output) {
		File outputFile = new File(output.getAbsolutePath() + ".xls");
		boolean mkFileSucceeded = false;
		try {
			//Creates the new xls file
			mkFileSucceeded = outputFile.createNewFile();
		} catch(IOException e) {
			System.err.println("Invalid output file path!");
		}
		if(mkFileSucceeded) {
			//saves the primaryValue (time)
			TransmittedValue primaryValue = input.getValues()[0];
			TransmittedValue[] values = new TransmittedValue[input.getValues().length-1];
			int valueIndex = 0;
			//for-loop to save all values into an TransmittedValue Array except of time
			for (TransmittedValue currentValue : input.getValues()) {
				if (valueIndex != 0) {
					values[valueIndex-1] = currentValue;
				}
				valueIndex ++;
			}
			try {
				//Creates a new Workbook
				Workbook workbook = new XSSFWorkbook();
				//Creates a new Sheet in Excel
				Sheet valueSheet = workbook.createSheet("Apollo 12 - Values");
				int currentRow = 0;
				int currentCell = 0;
				Row row = valueSheet.createRow(currentRow);
				//For-loop to create the header of the xls file
				for (TransmittedValue currentValue : input.getValues()) {
					Cell cell = row.createCell(currentCell);
					cell.setCellValue(currentValue.getKey() + "(" + currentValue.getUnit() + ")");
					currentCell++;
				}
				currentRow ++;
				currentCell = 0;
				//for-loop to write all the values into the file
				for (int lineIndex = 0; lineIndex < input.getDataOfKey(primaryValue.getKey()).length; lineIndex ++) {
					row = valueSheet.createRow(currentRow);
					Cell cell = row.createCell(currentCell);
					cell.setCellValue(Long.parseLong(input.getDate(primaryValue.getKey(), lineIndex)));
					for (TransmittedValue currentValue : values) {
						currentCell++;
						cell = row.createCell(currentCell);
						cell.setCellValue(Double.parseDouble(input.getDate(currentValue.getKey(), lineIndex)));
					}
					currentRow++;
					currentCell = 0;
				}
				int sheetIndex = 1;
				//for-loop to create all the charts
				for (TransmittedValue currentValue : values) {
					//Creating a new Sheet named like the actual key
					Sheet chartSheet = workbook.createSheet(currentValue.getKey());
					Drawing drawing = chartSheet.createDrawingPatriarch();
					ClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 0, 5, 10, 15);
					Chart chart = drawing.createChart(anchor);
					ChartLegend legend = chart.getOrCreateLegend();
					legend.setPosition(LegendPosition.TOP_RIGHT);
					ScatterChartData data = chart.getChartDataFactory().createScatterChartData();
				    ChartAxis xAxis = chart.getChartAxisFactory().createValueAxis(AxisPosition.BOTTOM);
				    ValueAxis yAxis = chart.getChartAxisFactory().createValueAxis(AxisPosition.LEFT);
				    //Create the x- and yAxis values
				    ChartDataSource<?> xValues = DataSources.fromNumericCellRange(valueSheet, new CellRangeAddress(1, valueSheet.getLastRowNum(), 0, 0));
				    ChartDataSource<Number> yValues = DataSources.fromNumericCellRange(valueSheet, new CellRangeAddress(1, valueSheet.getLastRowNum(), sheetIndex, sheetIndex));
				    //Add the values twice to the data
				    data.addSerie(xValues, yValues);
				    data.addSerie(xValues, yValues);
				    //Draw the chart
				    chart.plot(data, xAxis, yAxis);
				    sheetIndex++;
				}
				FileOutputStream outputStream = new FileOutputStream(outputFile);
			    workbook.write(outputStream);
			    outputStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}
